package com.lft.examsys.entity;


import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class User implements ValidationEntity {
    private Integer id;
    private String username;
    private String password;
    private String icon;
    private String roleId;
    private Date registerTime;
    private boolean banned;

    @TableField(exist = false)
    private List<GrantedAuthority> authorizes;

    public User() {

    }

    public User(String username, String password) {
        this.username = username;
        this.password = password;
    }

    public User(Integer id, String username, String password) {
        this.id = id;
        this.username = username;
        this.password = password;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getIcon() {
        return icon;
    }

    public void setIcon(String icon) {
        this.icon = icon;
    }

    public String getRoleId() {
        return roleId;
    }

    public void setRoleId(String roleId) {
        this.roleId = roleId;
    }

    private boolean preprocess() {
        return StringUtils.isNotEmpty(username) && StringUtils.isNotEmpty(password);
    }

    public Date getRegisterTime() {
        return registerTime;
    }

    public void setRegisterTime(Date registerTime) {
        this.registerTime = registerTime;
    }

    @Override
    public boolean valid() {
        if (!preprocess())
            return false;

        username = username.trim();
        password = password.trim();

        return true;
    }

    public String resolveRoleName(List<Role> roles) {
        for (Role role : roles) {
            if (role.getId().equalsIgnoreCase(roleId))
                return role.getName();
        }

        return "???";
    }

    public boolean isBanned() {
        return banned;
    }

    public boolean getBanned() {
        return banned;
    }

    public void setBanned(boolean banned) {
        this.banned = banned;
    }

    public void fillAuthorize(List<String> authorizes) {
        this.authorizes = new ArrayList<>();
        for (String authorize : authorizes) {
            this.authorizes.add(new SimpleGrantedAuthority(authorize));
        }
    }

    public List<GrantedAuthority> takeAuthorize() {
        return authorizes;
    }
}
